package com.yantong.service.impl;

import com.yantong.pojo.Centre;
import com.yantong.mapper.CentreMapper;
import com.yantong.service.CentreService;
import com.yantong.result.ResultVo;
import com.yantong.utils.DateUtils;
import com.yantong.utils.MD5Utils;
import com.yantong.utils.PageUtils;
import com.yantong.service.ConfigService;
import com.yantong.pojo.*;
import com.yantong.pojo.vo.OrderProductVo;
import com.yantong.mapper.*;
import com.yantong.service.UserService;
import com.yantong.mapper.MemberMapper;
import com.yantong.utils.SysUser;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 用户操作
 *
 * @author kanghaixin
 */
@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private UserRoleMapper userRoleMapper;
	@Autowired
	private UserCentreMapper userCentreMapper;
	@Autowired
	private LoginLogMapper loginLogMapper;
	@Autowired
	private OrderProductMapper orderProductMapper;
	@Autowired
	private ConfigService configService;
	@Autowired
	@Lazy
	private CentreService centreService;
	@Autowired
	private ProductCentreMapper productCentreMapper;
	@Autowired
    private MemberMapper memberMapper;
	@Autowired
    private WithdrawalsMapper withdrawalsMapper;
	@Autowired
    private OrderMapper orderMapper;
	@Autowired
    private  CentreMapper centreMapper;
	private static final Logger logger = LoggerFactory.getLogger(UserService.class);
	private static final String USER_CACHE_NAME = "user";
	private static final String ROLE_CACHE_NAME = "role";

	@Override
	@Cacheable(value = USER_CACHE_NAME, key = "#userId")
	public SysUser getUserById(Long userId) {
		if (userId == null) {
			logger.info("userId is null");
			return null;
		}
		return userMapper.getByKey(userId);
	}

	@Override
	@Cacheable(value = USER_CACHE_NAME, keyGenerator = "localKeyGenerator")
	public List<SysUser> getUserList(Map<String, Object> map) {
		return userMapper.getListByParams(map);
	}

	@Override
	@CacheEvict(value = { USER_CACHE_NAME, ROLE_CACHE_NAME }, allEntries = true)
	@Transactional(rollbackFor = Exception.class)
	public int saveUser(SysUser user,String roleIds) {
		if (StringUtils.isNotEmpty(roleIds)) {
			String[] strings = roleIds.split(",");
			List<Long> rl = new ArrayList<>();
			for (int i=0;i< strings.length;i++) {
				if (StringUtils.isNotEmpty(strings[i])) {
					rl.add(Long.parseLong(strings[i]));
				}
			}
			user.setRoleIds(rl);
		}
		String password = user.getPassword();
		user.setPassword(MD5Utils.encrypt(user.getName(), user.getPassword()));

		if (user == null) {
			logger.info("user is null,save failed!");
			return 0;
		}
		user.setStatus("1");
		int result = userMapper.insert(user);
		if (user.getCentreId() != null) {
			 Centre centre = centreService.getByKey(user.getCentreId());
			//用户站长
			 if(centre.getMid()!=null && centre.getMid()!=0 && user.getRoleIds().contains(new Long(5))) {
				 String url =  StringUtils.isEmpty(configService.getBaseConfig().getMallUrl()) ? "":configService.getBaseConfig().getMallUrl();
				 Member member = new Member();
				 member.setId(centre.getMid());
			     member.setQianming("尊敬的商户您好，您申请的商户后台账号:".concat(
			    		 user.getName()).concat("密码:").concat(password).concat("网址:").concat(url));
			     //更新用户信息
			     memberMapper.updateByPrimaryKeySelective(member);
			 }
			SysUserCentre userCentre = new SysUserCentre();
			userCentre.setCentreId(user.getCentreId());
			userCentre.setUserId(user.getUserId());
			userCentreMapper.saveUserCentre(userCentre);
		}

		if (CollectionUtils.isNotEmpty(user.getRoleIds())) {
			List<UserRole> list = new ArrayList<>();
			for (Long roleId : user.getRoleIds()) {
				UserRole userRole = new UserRole();
				userRole.setRoleId(roleId);
				userRole.setUserId(user.getUserId());
				list.add(userRole);
			}
			userRoleMapper.batchSave(list);
		}
		return result;
	}

	@Override
	@CacheEvict(value = { USER_CACHE_NAME, ROLE_CACHE_NAME }, allEntries = true)
	@Transactional(rollbackFor = Exception.class)
	public int updateUser(SysUser user) {
		if (user == null || user.getUserId() == null) {
			logger.info("user or userId is null");
			return 0;
		}
		if (CollectionUtils.isNotEmpty(user.getRoleIds())) {
			List<UserRole> list = new ArrayList<>();
			for (Long roleId : user.getRoleIds()) {
				UserRole userRole = new UserRole();
				userRole.setUserId(user.getUserId());
				userRole.setRoleId(roleId);
				list.add(userRole);
			}
			userRoleMapper.removeByUserId(user.getUserId());
			userRoleMapper.batchSave(list);
		}
		return userMapper.updateUser(user);
	}


	@Override
	@Cacheable(value = USER_CACHE_NAME, keyGenerator = "localKeyGenerator")
	public PageUtils<SysUser> listUsers(Map<String, Object> params, Integer offset, Integer limit) {
		PageUtils<SysUser> pageUtils = new PageUtils<>();
		int total = userMapper.countByParams(params);
		if (total > 0) {
			pageUtils.setRows(userMapper.getListByParams(params, new RowBounds(offset, limit)));
			pageUtils.setTotal(total);
		} else {
			pageUtils.setRows(new ArrayList<>());
		}
		return pageUtils;
	}

	@Override
//	@Cacheable(value = USER_CACHE_NAME, keyGenerator = "localKeyGenerator")
	public boolean checkExit(String username) {
		if (StringUtils.isEmpty(username)) {
			return false;
		}
		Map<String, Object> params = new HashMap<>(2);
		params.put("name", username);
		params.put("status", "1");
		if (userMapper.countByParams(params) > 0) {
			return true;
		}
		return false;
	}

	@Override
	@CacheEvict(value = USER_CACHE_NAME, allEntries = true)
	public int removeUser(Long userId, String flag) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (userId == null && flag.equals("")) {
			return 0;
		} else {
			map.put("userId", userId);
			map.put("flag", flag);
		}
		return userMapper.removeUser(map);
	}

	@Override
	@CacheEvict(value = USER_CACHE_NAME, allEntries = true)
	public int resetPsw(SysUser sysUser) {
		SysUser currentUser = userMapper.getByKey(sysUser.getUserId());
		//teamid存在，表示是门店ID，同时要修改门店用户的密码
		if(null != currentUser && currentUser.getTeamId() != null){
			String encPassword = MD5Utils.encrypt(sysUser.getPassword());
			Member shopMember = memberMapper.selectByPrimaryKey(currentUser.getTeamId());
			if(null != shopMember){
				shopMember.setPwd(encPassword);
				memberMapper.updateByPrimaryKey(shopMember);
			}
		}

		sysUser.setPassword(MD5Utils.encrypt(sysUser.getName(), sysUser.getPassword()));
		return userMapper.updateUser(sysUser);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(value = USER_CACHE_NAME, allEntries = true)
	public int updateLoginIp(Long userId, String ip) {
		if (userId == null || StringUtils.isEmpty(ip)) {
			return 0;
		}
		SysUser user = userMapper.getByKey(userId);
		if (user == null) {
			return 0;
		}
		LoginLog loginLog = new LoginLog();
		loginLog.setLoginIp(ip);
		loginLog.setUserId(userId);
		loginLogMapper.insertLog(loginLog);

		user.setLoginIp(ip);
		user.setLoginCount(user.getLoginCount() + 1);
		return userMapper.updateUser(user);
	}

	@Override
	public LoginLog getPreLoginLog(Long userId) {
		if (userId == null) {
			return null;
		}
		return loginLogMapper.getPreLog(userId);
	}




	@Override
	@Cacheable(value = USER_CACHE_NAME, key = "methodName + #userId")
	public SysUserCentre getUserCentre(Long userId) {
		return userCentreMapper.getUserCentre(userId);
	}



	/**
	 * 商户今日预计收益明细
	 *
	 * @param centreId
	 * @return
	 */
	@Override
	public PageUtils<OrderProductVo> getTodayCentreTotal(Long centreId, String starDt, String endDt,String baseId,
			String oppayStatus,String isafter,String opstatus,Integer offset,Integer limit) {
		if (centreId == null) {
			return null;
		}
		Date start = null;
		Date end = null;
		PageUtils<OrderProductVo> pageUtils = new PageUtils<>();
		if ((starDt.equals("") || starDt == null) && (endDt.equals("") || endDt == null)) {
			int startH = 20, startM = 30, endH = 20, endM = 0;
			TradeConfig config = configService.getTradeConfig(centreId);
			if (config != null) {
				startH = config.getNodeHour() == null ? startH : config.getNodeHour();
				startM = config.getNodeMin() == null ? startM : config.getNodeMin();
				endH = config.getFreeEndHour() == null ? endH : config.getFreeEndHour();
				endM = config.getFreeEndMin() == null ? endM : config.getFreeEndMin();
			}
			start = DateUtils.getAppointTime(DateUtils.getAddDayDate(new Date(), -1), startH, startM);
			end = DateUtils.getAppointTime(new Date(), endH, endM);
		} else {
			start = DateUtils.parseDateForm(starDt);
			end = DateUtils.parseDateForm(endDt);
		}
		int total = orderProductMapper.countByParams(centreId, start, end,baseId,oppayStatus,isafter,opstatus);
		if (total > 0) {
			List<OrderProductVo> returnList = orderProductMapper.getTodayOrdList(centreId, start, end,baseId,
					oppayStatus,isafter,opstatus,new RowBounds(offset, limit));
			pageUtils.setRows(returnList);
			pageUtils.setTotal(total);
		} else {
			pageUtils.setRows(new ArrayList<>());
		}
		return pageUtils;
	};

	/**
	 * 商户今日收益
	 *
	 * @param centreId
	 * @param starDt
	 * @param endDt
	 * @return
	 */
	public OrderProductVo getTodayCash(Long centreId, String starDt, String endDt,String baseId,
			String oppayStatus,String isafter,String opstatus) {
		OrderProductVo orderProductVo = new OrderProductVo();
		Date start = null;
		Date end = null;
		if ((starDt.equals("") || starDt == null) && (endDt.equals("") || endDt == null)) {
			int startH = 20, startM = 30, endH = 20, endM = 0;
			TradeConfig config = configService.getTradeConfig(centreId);
			if (config != null) {
				startH = config.getNodeHour() == null ? startH : config.getNodeHour();
				startM = config.getNodeMin() == null ? startM : config.getNodeMin();
				endH = config.getFreeEndHour() == null ? endH : config.getFreeEndHour();
				endM = config.getFreeEndMin() == null ? endM : config.getFreeEndMin();
			}
			start = DateUtils.getAppointTime(DateUtils.getAddDayDate(new Date(), -1), startH, startM);
			end = DateUtils.getAppointTime(new Date(), endH, endM);
		} else {
			start = DateUtils.parseDateForm(starDt);
			end = DateUtils.parseDateForm(endDt);
		}
		// 得到今日商户订单量
		List<OrderProductVo> list = orderProductMapper.getTodayOrdListSumMoney(centreId, start, end,baseId,oppayStatus,isafter,opstatus);
		/**
		 * 手续费
		 */
		BigDecimal poundage = null;
		/**
		 * 商户收益
		 */
		BigDecimal money = new BigDecimal("0");
		/**
		 * 门店总计
		 */
		BigDecimal teammoney = new BigDecimal("0");
		/**
		 * 手续费总计
		 */
		BigDecimal sumpoundage = new BigDecimal("0");
		/*SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
		Object moneyObj = null;
		Object teammoneyObj = null;
		Object sumpoundageObj = null;
		//结束时间如果不是今天的日期
		if(!df.format(new Date()).equals(df.format(end))) {
			moneyObj = localRedis.get("money"+starDt+endDt+baseId+oppayStatus+isafter+opstatus+centreId);
			teammoneyObj = localRedis.get("teammoney"+starDt+endDt+baseId+oppayStatus+isafter+opstatus+centreId);
			sumpoundageObj = localRedis.get("sumpoundage"+starDt+endDt+baseId+oppayStatus+isafter+opstatus+centreId);
		}*/

		if(!isafter.equals("1")) {
		/*	//没有存入缓存就查找
			if(moneyObj==null && teammoneyObj==null && sumpoundageObj==null) {*/
				for (OrderProductVo op : list) {
					ProductCentre pc = productCentreMapper.getByKey(op.getProductId());
					CentreRate cr = centreService.getRateByCentreId(centreId);
					if (cr != null) {
						if (cr.getTradeRate() != null) {
							poundage = op.getPrice().multiply(cr.getTradeRate()).divide(BigDecimal.valueOf(1000), 4,
									BigDecimal.ROUND_HALF_UP);
							sumpoundage = sumpoundage.add(poundage);
						}
					}
					if (pc.getProductId() == null || pc.getProductId() == 0) {
						money = money.add((op.getMarketprice()).multiply(BigDecimal.valueOf(op.getTotal())).subtract(poundage));
					} else {
						money = money.add((op.getMarketprice().subtract(op.getCostprice()))
								.multiply(BigDecimal.valueOf(op.getTotal())).subtract(poundage));
					}
					//门店佣金累加 佣金乘以商品数量
					teammoney = teammoney.add(op.getHeadcommission().multiply(BigDecimal.valueOf(op.getTotal())));
				}
				/*//结束时间如果不是今天的日期就存入缓存
				if(!df.format(new Date()).equals(df.format(end))) {
					 localRedis.set("money"+starDt+endDt+baseId+oppayStatus+isafter+opstatus+centreId,money);
				     localRedis.set("teammoney"+starDt+endDt+baseId+oppayStatus+isafter+opstatus+centreId,teammoney);
					 localRedis.set("sumpoundage"+starDt+endDt+baseId+oppayStatus+isafter+opstatus+centreId,sumpoundage);
				}
			}else {
				money = (BigDecimal)moneyObj;
				teammoney = (BigDecimal)teammoneyObj;
				sumpoundage = (BigDecimal)sumpoundageObj;
			}	*/
		}

		//售后统计
		BigDecimal	sumAfter = new BigDecimal(orderProductMapper.getTodaySumAfter(centreId, start, end, baseId));
		//供应商支出
		BigDecimal	sumSup = new BigDecimal(orderProductMapper.getTodaySumSup(centreId, start, end));
		if( !isafter.equals("1")) {
			// 添加站点预计收益
			orderProductVo.setMoney(money);
			// 添加门店预计收益总计
			orderProductVo.setTeammoney(teammoney);
			//商户手续费总计
			orderProductVo.setPoundage(sumpoundage);
		}
		if(!isafter.equals("0")) {
		//商户售后统计(区分平台商品售后 站点售后) （状态为6，并且isafter为1的订单统计）
		orderProductVo.setSumAfter(sumAfter);
		}
		//供应商支出 站点（站点供应商的成本统计）
		orderProductVo.setSumSup(sumSup);
		//未选择售后
		if(isafter.equals("") || isafter==null) {
			//实际收入（所有状态订单减去团场佣金减去供应商减去售后） 状态可选如果要看实际真是收入的还状态选择已完成6即可
			orderProductVo.setRealIncome(money.subtract(teammoney).subtract(sumAfter).subtract(sumSup));
		}else if(isafter.equals("0")){
			//未售后
			//实际收入（所有状态订单减去团场佣金减去供应商） 状态可选如果要看实际真是收入的还状态选择已完成6即可
			orderProductVo.setRealIncome(money.subtract(teammoney).subtract(sumSup));
		}

		return orderProductVo;
	};

	 /**
	  * 商户明细数据集合
	  * @param centreId
	  * @param starDt
	  * @param endDt
	  * @param baseId
	  * @return
	  */
	public  List<OrderProductVo> getTodayOrdList(Long centreId, String starDt, String endDt,String baseId,
			String oppayStatus,String isafter,String opstatus){
		Date start = null;
		Date end = null;
		if ((starDt.equals("") || starDt == null) && (endDt.equals("") || endDt == null)) {
			int startH = 20, startM = 30, endH = 20, endM = 0;
			TradeConfig config = configService.getTradeConfig(centreId);
			if (config != null) {
				startH = config.getNodeHour() == null ? startH : config.getNodeHour();
				startM = config.getNodeMin() == null ? startM : config.getNodeMin();
				endH = config.getFreeEndHour() == null ? endH : config.getFreeEndHour();
				endM = config.getFreeEndMin() == null ? endM : config.getFreeEndMin();
			}
			start = DateUtils.getAppointTime(DateUtils.getAddDayDate(new Date(), -1), startH, startM);
			end = DateUtils.getAppointTime(new Date(), endH, endM);
		} else {
			start = DateUtils.parseDateForm(starDt);
			end = DateUtils.parseDateForm(endDt);
		}
		return orderProductMapper.getTodayOrdListSumMoney(centreId, start, end,baseId,oppayStatus,isafter,opstatus);
	};


	 /**
	  * 得到默认时间
	  * @return
	  */
	public ResultVo getDefaultTime(Long centreId) {
		ResultVo resultVo = new ResultVo();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
			int startH = 20, startM = 30, endH = 20, endM = 0;
			TradeConfig config = configService.getTradeConfig(centreId);
			if (config != null) {
				startH = config.getNodeHour() == null ? startH : config.getNodeHour();
				startM = config.getNodeMin() == null ? startM : config.getNodeMin();
				endH = config.getFreeEndHour() == null ? endH : config.getFreeEndHour();
				endM = config.getFreeEndMin() == null ? endM : config.getFreeEndMin();
			}
			Date	start = DateUtils.getAppointTime(DateUtils.getAddDayDate(new Date(), -1), startH, startM);
			Date end = DateUtils.getAppointTime(new Date(), endH, endM);
			resultVo.put("startDt", df.format(start));
			resultVo.put("endDt",  df.format(end));
		return resultVo;
	};

	@Override
	public SysUser getUserByName(String name) {
		return userMapper.getUserByName(name);
	}

	 /**
	  * 得到平台账户金额信息
	  * @return
	  */
	public  Map<String,Object> getAccountInfo(){
		Map<String,Object> returnVal = new HashMap<String,Object>();
		//所有较色账户余额总和
		 String accountSumMoney =  memberMapper.getAllRoleSumMoney();
		 //得到所有角色提现未审核未打款的金额
		 String sumBalance = withdrawalsMapper.getAllRoleBalance();
		 //得到今天下单支付完成代发货的订单金额
		String sumPrice =  orderMapper.getAllOrderPriceByStu();
		  //得到锁哦与订单 已支付已收获的成本价
		String sumCostprice = 	orderProductMapper.getallOrdProByStu();
		//得到所有站点账户余额
		String sumContreBalance = centreMapper.getAllCentreBalance();
		 if(StringUtils.isNotEmpty(accountSumMoney)) {
			 returnVal.put("accountSumMoney", accountSumMoney);
		 }
		 if(StringUtils.isNotEmpty(sumBalance)) {
			 returnVal.put("sumBalance", sumBalance);
		 }
		 if(StringUtils.isNotEmpty(sumPrice)) {
			 returnVal.put("sumPrice", sumPrice);
		 }
		 if(StringUtils.isNotEmpty(sumCostprice)) {
			 returnVal.put("sumCostprice", sumCostprice);
		 }
		 if(StringUtils.isNotEmpty(sumContreBalance)) {
			 returnVal.put("sumContreBalance", sumContreBalance);
		 }
		return returnVal;
	}

}
